<?php
namespace App\DBs;

use App\Utility\Sms;
use Illuminate\Support\Facades\DB;

class UserDB extends BaseDB
{
    /**
     * 用户
     * name 用户名
     * phone 手机号码
     * password 加密密码
     * head 头像
     * detail 个人签名
     * sysType 用户系统类型：1普通用户，2系统管理员，
     * userType 用户等级：
     */

    /**
     * 验证码
     * phone 手机号码
     * yzm 验证码
     * status 发送状态：1失败，2成功，
     */

    protected $table = 'user';
    protected $tLogin = 'user_login';
    protected $tYzm = 'user_yzm';

    public function __construct()
    {
    }

    /**
     * 发送验证码
     */
    public function setYzm($phone)
    {
        $yzm = $this->getRandYzm(4);
        //保存验证码
        $lastId = DB::table($this->tYzm)->insertGetId([
            'phone' => $phone,
            'yzm' => $yzm,
            'created_at' => time(),
        ]);
        if (!$lastId) {
            return array('code'=>-1, 'msg'=>'验证码保存失败');
        }
        //发送短信
        $smsMsg = '您的验证码是：'.$yzm.'，当天有效！';
        $sms = new Sms();
        $resSms = $sms->send($phone,$smsMsg);
        /**
         * {
            "code": "0",
            "msgId": "20022014555600202009000046404923",
            "time": "20200220145556",
            "errorMsg": ""
            }
         */
        if ($resSms['code']!=0) {
            return array('code'=>-2, 'msg'=>'验证码发送失败');
        }
        //更新验证码状态
        DB::table($this->tYzm)->where('id',$lastId)
            ->update(['status'=>2]);
        $dataArr = array(
            'lastId' => $lastId,
        );
        return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
//        //开启事务
//        DB::beginTransaction();
//        try {
//            //提交事务
//            DB::commit();
//            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
//        } catch (\Exception $e) {
//            //事务回滚
//            DB::rollBack();
//            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
//        }
    }

    /**
     * 验证码获取
     */
    public function getYzm($phone,$yzm)
    {
        $start = strtotime(date('Ymd',time()).'000001');
        $end = strtotime(date('Ymd',time()).'235959');
        $model = DB::table($this->tYzm)->where('phone',$phone)
            ->where('yzm',$yzm)
            ->where('status',2)
            ->where('created_at','>=',$start)
            ->where('created_at','<=',$end)
            ->orderBy('id','desc')
            ->first();
        return $model ? $this->jsonToArr($model) : array();
    }

    /**
     * 获取用户信息，通过UID
     */
    public function getOneByUid($uid)
    {
        $model = DB::table($this->table)->where('id',$uid)->first();
        return $model ? $this->jsonToArr($model) : array();
    }

    /**
     * 获取用户信息，通过手机号码
     */
    public function getOneByPhone($phone)
    {
        $model = DB::table($this->table)->where('phone',$phone)->first();
        return $model ? $this->jsonToArr($model) : array();
    }

    /**
     * 新增用户
     */
    public function setAdd($phone,$pwd)
    {
        $name = 'tsh'.date('YmdHis',time()).rand(10000,99999);
        $password = md5($pwd);
        $lastId = DB::table($this->table)->insertGetId([
            'name' => $name,
            'phone' => $phone,
            'password' => $password,
            'created_at' => time(),
        ]);
        return $lastId;
    }

    /**
     * 新增登陆日志
     */
    public function setLoginAdd($phone)
    {
        $lastId = DB::table($this->tLogin)->insertGetId([
            'phone' => $phone,
            'created_at' => time(),
        ]);
        return $lastId;
    }

    /**
     * 更新昵称
     */
    public function setNick($uid,$nick)
    {
        DB::table($this->table)->where('id',$uid)
            ->update([
                'name' => $nick,
                'updated_at' => time(),
            ]);
        return true;
    }

    /**
     * 更新密码
     */
    public function setPwd($uid,$pwdmd5)
    {
        DB::table($this->table)->where('id',$uid)
            ->update([
                'password' => $pwdmd5,
                'updated_at' => time(),
            ]);
        return true;
    }

    /**
     * 头像上传，临时数据更新
     * @param $stamp 用户上传标识
     * @param $uid 用户UID
     * @param $path 用户本地地址
     */
    public function setHeadUpdate($stamp, $uid, $path)
    {
        if (!$stamp || !$uid) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        $fileTmps = DB::table($this->tFileTmp)
            ->where('stamp',$stamp)
            ->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        if (!count($fileTmps)) {
            return array('code'=>'-2', 'msg'=>'数据错误');
        }
        $fileTmp = $this->jsonToArr($fileTmps[0]);
        $filePath = $fileTmp['filePath'];
//        return $filePath;
        //开启事务
        DB::beginTransaction();
        try {
            //更新临时信息
            DB::table($this->tFileTmp)
                ->where('stamp',$stamp)
                ->update([
                    'stamp' => $stamp,
                    'uid' => $uid,
                    'localAppPath' => $path,
                    'updated_at' => time(),
                ]);
            //更新用户头像
            DB::table($this->table)->where('id',$uid)
                ->update([
                    'head' => $filePath,
                    'localAppHead' => $path,
                    'updated_at' => time(),
                ]);
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 头像背景上传，临时数据更新
     * @param $stamp 用户上传标识
     * @param $uid 用户UID
     * @param $path 用户本地地址
     */
    public function setHeadBgUpdate($stamp, $uid, $path)
    {
        if (!$stamp || !$uid) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        $fileTmps = DB::table($this->tFileTmp)
            ->where('stamp',$stamp)
            ->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        if (!count($fileTmps)) {
            return array('code'=>'-2', 'msg'=>'数据错误');
        }
        $fileTmp = $this->jsonToArr($fileTmps[0]);
        $filePath = $fileTmp['filePath'];
        //开启事务
        DB::beginTransaction();
        try {
            //更新临时信息
            DB::table($this->tFileTmp)
                ->where('stamp',$stamp)
                ->update([
                    'stamp' => $stamp,
                    'uid' => $uid,
                    'localAppPath' => $path,
                    'updated_at' => time(),
                ]);
            //更新用户头像
            DB::table($this->table)->where('id',$uid)
                ->update([
                    'headbg' => $filePath,
                    'localAppHeadBg' => $path,
                    'updated_at' => time(),
                ]);
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}